using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Systems.Security;
using Deepcode.Flux.Core.Services.State;
using Deepcode.Flux.Core.Extensions;
using Deepcode.Flux.Core.Systems.Audit.Quick;

public partial class Private_Config_Groups_ui_Form : Deepcode.Flux.Core.UI.AdministrationModulePage
{
	#region Permission Code Override
	public override string RequiredPermissionCode { get { return "FluxSecGroups"; } }
	#endregion
	#region ViewState storage
	/// <summary>
	/// Stores the state of the listing view
	/// </summary>
	public string ListingState
	{
		get
		{
			return (string)ViewState["ListingState"];
		}
		set
		{
			ViewState["ListingState"] = value;
		}
	}
	/// <summary>
	/// Stores the ID of the record being edited
	/// </summary>
	public int RecordID
	{
		get
		{
			object o = ViewState["RecordID"];
			if (o == null) return -1;
			return (int)o;
		}
		set
		{
			ViewState["RecordID"] = value;
		}
	}
	#endregion
	#region Page Load Event
	/// <summary>
	/// Page Load event
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			// Store any state information from the calling listing
			this.ListingState = GetAttribute("state", "");
			this.RecordID = GetAttribute("ID", -1);

			// Load the record if specified
			if (this.RecordID != -1)
			{
				AdministrationGroups groups = new AdministrationGroups();
				AdministrationGroup group = groups.GetGroupByID(this.RecordID);
				if (group == null) GoBack();

				GroupName.Text = group.GroupName;
			}
			// Setup the UI. 
			PopulatePermissions();
		}
	}
	#endregion
	#region Navigation
	/// <summary>
	/// Returns to the listing, restoring state
	/// </summary>
	protected void GoBack()
	{
		string url = String.Format("default.aspx?state={0}", this.ListingState);
		Response.Redirect(url, true);
	}
	#endregion
	#region Save/Cancel handlers
	/// <summary>
	/// User cancelled the save, go back to previous page
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnCancel_Click(object sender, EventArgs e)
	{
		GoBack();
	}
	/// <summary>
	/// User clicked the save button, store the data
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnSave_Click(object sender, EventArgs e)
	{
		if (!Page.IsValid) return;
		AdministrationGroups groups = new AdministrationGroups();
		AdministrationGroup group = null;

		if (this.RecordID != -1)
		{
			// Load the existing record and ensure it still exists
			group = groups.GetGroupByID(this.RecordID);
			if (group == null) GoBack();
		}
		else
			group = new AdministrationGroup();

		// Set the group name and save the record
		group.GroupName = this.GroupName.Text;
		groups.Save(group);

		// Get the selected group codes and save them
		string[] selectedPermissions = GetSelectedPermissionCodes();
		groups.SetPermissions(group.PK_ID, selectedPermissions);

		QuickAudit.RaiseInformation(
			new AuditUser(),
			"Flux", "Group manager",
			"created/edited group {0} ({1})",
			group.PK_ID, group.GroupName);
		
		GoBack();
	}
	#endregion

	#region Data functions for permissions repeater
	/// <summary>
	/// Loads the permissions checkbox list
	/// </summary>
	private void PopulatePermissions()
	{
		// Get the known permission groups from the addin tree
		AddinTreeNode root = AddinTree.Tree.GetTreeNodeNoThrow("/Flux/Security/Permissions");
		if (root == null) return;

		PermissionGroup[] groups = root.BuildChildItems(this).ToArray(typeof(PermissionGroup)) as PermissionGroup[];
		PermissionGroups.DataSource = groups;
		PermissionGroups.DataBind();
	}
	/// <summary>
	/// Item added to permission groups repeater - needs to populate the label
	/// and the checkbox list with individual permissions.
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void PermissionGroups_ItemDataBound(object sender, RepeaterItemEventArgs e)
	{
		// Load the group if we have one
		AdministrationGroups g = new AdministrationGroups();
		AdministrationGroup theGroup = g.GetGroupByID(this.RecordID);

		// Find the controls on the row
		PermissionGroup group = (PermissionGroup)e.Item.DataItem;
		CheckBoxList cbl = (CheckBoxList)e.Item.FindControl("PermissionsList");
		Label pgt = (Label)e.Item.FindControl("PermissionGroupTitle");
		// Ensure we have everything required
		if (group == null || cbl == null || pgt == null) return;

		// Set the permission group title label
		pgt.Text = group.GroupName;

		// Enumerate all of the permissions in the permission group
		foreach (Permission p in group.Permissions)
		{
			// Create a checkbox item
			ListItem item = new ListItem();
			item.Text = p.Title;
			item.Value = p.Code;
			// If we're editing a group, set selections
			if (theGroup != null)
			{
				foreach (AdminGroupPermission gp in theGroup.Permissions)
					if (gp.Permission == p.Code)
					{
						item.Selected = true;
						break;
					}
			}
			// Add the item to the check box list
			cbl.Items.Add(item);
		}
	}
	/// <summary>
	/// This function interrogates the various checkbox lists to determine
	/// what permission codes have been selected.
	/// </summary>
	/// <returns></returns>
	private string[] GetSelectedPermissionCodes()
	{
		ArrayList items = new ArrayList();

		// Loop over each permission group in the repeater
		foreach (RepeaterItem item in PermissionGroups.Items)
		{
			// Get the checkbox list for the repeater item
			CheckBoxList cbl = (CheckBoxList)item.FindControl("PermissionsList");
			if (cbl != null)
			{
				// Get the list of selected codes from the list
				string[] sels = Deepcode.Flux.Core.Services.Assistant.ControlUtil.GetListSelectedStrings(cbl.Items);
				// Append them to the master list
				foreach (string s in sels)
					items.Add(s);
			}
		}
		// Return the master list as an array of strings
		return items.ToArray(typeof(string)) as String[];
	}
	#endregion
}
